package app.hanxiao.com.demo.push.Factory;

import android.content.Context;
import android.util.Log;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoService;
import org.apache.mina.core.service.IoServiceListener;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;

/**
 * 作者：韩笑 on 2017/6/8 0008 08:09
 * <p>
 * 作用：
 */


public class IoListener implements IoServiceListener {
    public NioSocketConnector connector;
    private Context context;
    private String ID;
    private String ADDRESS = "";
    private int PORT = 0;
    private static final String TAG = "PushServer";
    private static final int REPEAT_TIME = 100;//重连最大次数
    public IoListener(NioSocketConnector connector){
        this.connector = connector;
    }
    public IoListener(NioSocketConnector connector, String ID){
        this.connector = connector;
        this.ID = ID;
    }
    public IoListener(NioSocketConnector connector, String ID,String ADDRESS,int PORT){
        this.connector = connector;
        this.ID = ID;
        this.ADDRESS = ADDRESS;
        this.PORT = PORT;
    }
    @Override
    public void serviceActivated(IoService ioService) throws Exception {

    }

    @Override
    public void serviceIdle(IoService ioService, IdleStatus idleStatus) throws Exception {

    }

    @Override
    public void serviceDeactivated(IoService ioService) throws Exception {

    }

    @Override
    public void sessionCreated(IoSession ioSession) throws Exception {

    }

    @Override
    public void sessionClosed(IoSession ioSession) throws Exception {

    }

    @Override
    public void sessionDestroyed(IoSession ioSession) throws Exception {
        repeatConnect("");
    }
    /*
    * 断线重连操作
    * @param content
    */
    public void repeatConnect(String content)
    {
        // 执行到这里表示Session会话关闭了，需要进行重连,我们设置每隔3s重连一次,如果尝试重连5次都没成功的话,就认为服务器端出现问题,不再进行重连操作
        int count = 0;// 记录尝试重连的次数
        while (true) {
            try {
                count++;// 重连次数加1
                ConnectFuture future = connector.connect(new InetSocketAddress(
                        "192.168.1.104", 2000));
                future.awaitUninterruptibly();// 一直阻塞住等待连接成功
                IoSession session = future.getSession();// 获取Session对象
                BufferedReader inputReader = null;
                try {
                    inputReader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(ID.getBytes("utf-8"))));
                    String inputContent ;
                    while (!(inputContent = inputReader.readLine()).equals("bye")) {
                        session.write(inputContent);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (session.isConnected()) {
                    // 表示重连成功
                    Log.d(TAG,content  + " : 断线重连" + count + "次之后成功.....MapId" + ID);
                    count = 0;
                    break;
                }
            } catch (Exception e) {
                if (count == REPEAT_TIME) {
                    Log.d(TAG,content + " : 断线重连"
                            + REPEAT_TIME + "次之后仍然未成功,结束重连.....");
                    break;
                } else
                {
                    Log.d(TAG,content +  " : 本次断线重连失败,3s后进行第" + (count + 1) + "次重连.....");
                    try {
                        Thread.sleep(3000);
                        Log.d(TAG,content +  " : 开始第"+(count + 1)+"次重连.....");
                    } catch (InterruptedException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        }
    }
}

